<!--
 * createor: zc
 * email: zc8023zs@163.com
 * create_time: 2020/3/14 13:46:24
 *-->
<template>
  <div class="app-container">  
    <div class="filter-container">
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate"
          v-show="permissions.p_add">
            {{ $t('table.add') }}
        </el-button> 
    </div>
    <el-table
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      border
      row-key="id">
      <el-table-column
        show-overflow-tooltip
        prop="dept_name"
        label="部门名称"
        width="180">
      </el-table-column>
      <el-table-column
        prop="note"
        label="备注"
        width="300">
      </el-table-column>
      <el-table-column
        prop="sort"
        label="排序">
      </el-table-column> 
      <el-table-column v-if="permissions.operation" :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)" v-show="permissions.p_edit">
            {{ $t('table.edit') }}
          </el-button> 
          <el-button  size="mini" type="danger" @click="handleDelete(row)" v-show="permissions.p_del">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal='false' :visible.sync="dialogFormVisible" append-to-body>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="padding:0 100px 0 50px;">
        <el-form-item label="部门名称" prop="dept_name">
          <el-input maxlength="31" v-model.trim="temp.dept_name" />
        </el-form-item>  
        <el-form-item label="所属部门">
          <treeselect
              :options="deptTreeData"
              :default-expand-level="1"
              placeholder="请选择所属部门"
              v-model="tree"
              :normalizer="normalizer"
            />
        </el-form-item>  
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="temp.sort" :max="1000" :min="0"/>
        </el-form-item> 
        <el-form-item label="备注" prop="note">
          <el-input maxlength="101" v-model="temp.note" />
        </el-form-item> 

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog> 
  </div>
</template>

<script>
import { getSysDeptList, fetchObj, createObj, updateObj,deleteObj } from '@/api/project/system/project_sys_sys_dep'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { Loading } from 'element-ui';
// import the component
import treeselect from "@riophae/vue-treeselect";
// import the styles
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: 'a_systema_sys_dept',
  components: { Pagination,treeselect },
  filters: {
  },
  data() {
    return {
       tableKey: 0,
      temp: {
        id: 0,
        dept_name: '',
        note: '',
        sort: 0,
        pid: null,
        pname: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      tree:null,
      textMap: {
        update: '编辑',
        create: '添加'
      }, 
      rules: {
        dept_name: [{ required: true, message: '部门名称必填', trigger: 'change' }],
        sort: [{ type: "number", max:999, message: "排序不超过3位数", trigger: "blur"},
          {pattern: /^[+]{0,1}(\d+)$/, message: "排序为正整数", trigger: "change" }],
        note: [{ type: "string", max: 100, message: "备注不超过100个字", trigger: "blur"} ],
      }, 
      deptTreeData:[],
      defaultProps: {
        label: 'dept_name',
        children: 'children'
      },
      tableData: [],
      permissions:{
        p_add:false,
        p_edit: false,
        p_del: false,
        operation: false,
      }
    }
  },
  created() {
    this.getList()
    this.$per(result=>{
      this.permissions.p_add=result['*/system/sysdept/addSysDept']!=null;
      this.permissions.p_edit=result['*/system/sysdept/updateSysDept']!=null;
      this.permissions.p_del=result['*/system/sysdept/deleteSysDept']!=null;
      if(result['*/system/sysdept/updateSysDept']!=null || result['*/system/sysdept/deleteSysDept']!=null){
            this.permissions.operation=true;
      }
    })
  },
  methods: {
    table_index(index) {
      return (
        (this.listQuery.page - 1) * this.listQuery.size+
        index +
        1
      );
    },
    openFullScreen() {
        const loading = this.$loading({
          lock: true,
          text: '数据处理中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.2)'
        }); 
        setTimeout(() => {
          loading.close();
        }, 2000);
    },
    normalizer(node) {
      if (node.children == undefined || node.children == null || node.children.length==0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.dept_name,
        children: node.children
      };
    },
    getList() { 
      getSysDeptList(this.listQuery).then(response => {
        this.tableData = response.dataArray.dataList
        this.deptTreeData =  response.dataArray.dataList; 
      })
    },
    handleFilter() {
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: '',
        dept_name: '',
        note: '',
        level:0,
        sort: 0,
        pid: null,
        pname: '顶级部门'
      },
      this.tree=null;
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.openFullScreen();
          if(this.tree==""|| this.tree==null || this.tree==undefined){
            this.temp.pid=0;
          }else{
            this.temp.pid=this.tree;
          }
          createObj(this.temp).then(res => { 
            this.handleFilter();
            this.dialogFormVisible = false
            if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            }else{
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
                duration: 2000
              });
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      if(this.temp.pid==0){
        this.tree=null;
      }else{
        this.tree=this.temp.pid;
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.openFullScreen();
          if(this.tree==""|| this.tree==null || this.tree==undefined){
            this.temp.pid=0;
          }else{
            this.temp.pid=this.tree;
          }
          const tempData = Object.assign({}, this.temp)  
          tempData.children='';
          updateObj(tempData).then(res => { 
            this.handleFilter();
            this.dialogFormVisible = false;
            if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            }else{
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
                duration: 2000
              });
            }
          })
        }
      })
    },
    handleDelete(row) { 
      this.$confirm('确定删除该部门？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.openFullScreen();
        deleteObj(row).then(res=>{ 
          this.handleFilter();
          if (res.code == 0) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
                duration: 2000
              });
            }else{
              this.$notify({
                title: "失败",
                message: res.msg,
                type: "error",
                duration: 2000
              });
            }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
  }
}
</script>